from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from apps.spit.models import Spit

class SpitModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Spit
        fields = '__all__'
        extra_kwargs = {
            'userid': {'read_only': True},
            'nickname': {'read_only': True},
            'avatar': {'read_only': True}
        }

    def create(self, validated_data):
        spit = super().create(validated_data)

        try:
            user = self.context["request"].user
        except:
            user = None

            #    判断是否是评论别人
        if spit.parent:
            # 评论别人必须登陆
            if user and user.is_authenticated:
                spit.parent.comment += 1
                spit.parent.save()
                return spit
            else:
                raise ValidationError('未登录')
        else:
            return spit


